package com.css.dzj.dzjap.modules.administration.punish.service.impl;
import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.common.util.SnowflakeId;
import com.css.dzj.dzjap.modules.administration.punish.entity.Punish;
import com.css.dzj.dzjap.modules.administration.punish.entity.QPunish;
import com.css.dzj.dzjap.modules.administration.punish.mapper.PunishMapper;
import com.css.dzj.dzjap.modules.administration.punish.service.PunishService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import com.querydsl.core.types.dsl.NumberExpression;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class PunishServiceImpl implements PunishService {

    @Autowired
    private PunishMapper punishMapper;

    //注入JPAQueryFactory工厂
    @Autowired
    JPAQueryFactory jpaQueryFactory;
    @Autowired
    ServiceUtil serviceUtil;

    //查询行政处罚行为信息表
    @Override
    public Punish getPunish(String id) {
        if(StringUtils.isEmpty(id)){

            throw new RuntimeException("参数为空");
        }
        QPunish qPunish = QPunish.punish;
        return jpaQueryFactory
                .selectFrom(qPunish)
                .where( qPunish.id.eq(id),
                        qPunish.delFlag.eq(Constant.NO_DELETE)
                )
                .fetchOne();
    }

    // 添加行政处罚行为信息表
    @Override
    @Transactional
    public String addPunish(Punish push) {

        push.setDelFlag(Constant.NO_DELETE);
        push.setId(SnowflakeId.getId());
        push.setCreateTime(new Date());
        try {
            punishMapper.save(push);
            return push.getId();

        }catch (Exception e){
            return "0";
        }
    }

    // 修改行政处罚行为信息表
    @Override
    @Transactional
    public void update(Punish push) {

    }

    // 删除行政处罚行为信息表
    @Override
    @Transactional
    public Boolean deletePunish(String id) {
        QPunish qPunish = QPunish.punish;
        if(StringUtils.isEmpty(id)){
            return  false;
        }
        try{
            jpaQueryFactory
                    .update(qPunish)
                    .set(qPunish.delFlag,Constant.DELETE)
                    .where(
                            qPunish.delFlag.eq(Constant.NO_DELETE),
                            qPunish.id.eq(id)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     *分页查询所有行政处罚行为信息表
     */
    @Override
    public QueryResults<Punish> getAllPunish(Pageable pageable) {
        QPunish qPunish = QPunish.punish;
        Predicate predicate = qPunish.isNotNull().or(qPunish.isNull());
        predicate = ExpressionUtils.and(predicate, qPunish.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(qPunish)
                .where(
                        predicate
                )
                .orderBy(qPunish.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 多条件查询所有行政处罚行为信息表
     */
    @Override
    public QueryResults<Punish> getAllConPunish(Pageable pageable, String recordUniqueIdentity, String superviseItemCode, String punishActionName, String punishActionCode, String implementInstitution, String implementInstitutionCode) {
        QPunish qPunish = QPunish.punish;
        Predicate predicate = qPunish.isNotNull().or(qPunish.isNull());
        predicate = ExpressionUtils.and(predicate, qPunish.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ("".equals(recordUniqueIdentity) || recordUniqueIdentity == null) ? predicate : ExpressionUtils.and(predicate, qPunish.recordUniqueIdentity.like("%"+recordUniqueIdentity+"%"));
        predicate = ("".equals(superviseItemCode) || superviseItemCode == null) ? predicate : ExpressionUtils.and(predicate, qPunish.superviseItemCode.like("%"+superviseItemCode+"%"));
        predicate = ("".equals(punishActionName) || punishActionName == null) ? predicate : ExpressionUtils.and(predicate, qPunish.punishActionName.like("%"+punishActionName+"%"));
        predicate = ("".equals(punishActionCode) || punishActionCode == null) ? predicate : ExpressionUtils.and(predicate, qPunish.punishActionCode.like("%"+punishActionCode+"%"));
        predicate = ("".equals(implementInstitution) || implementInstitution == null) ? predicate : ExpressionUtils.and(predicate, qPunish.implementInstitution.like("%"+implementInstitution+"%"));
        predicate = ("".equals(implementInstitutionCode) || implementInstitutionCode == null) ? predicate : ExpressionUtils.and(predicate, qPunish.implementInstitutionCode.like("%"+implementInstitutionCode+"%"));

        return  jpaQueryFactory
                .selectFrom(qPunish)
                .where(
                        predicate
                )
                .orderBy(qPunish.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();


    }

    @Override
    public HashMap getCount() {
        QPunish q=QPunish.punish;
        List<Punish> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        HashMap map=new HashMap();
        for (Punish punish:list) {
            String address=punish.getImplementInstitution();
            Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.implementInstitution.eq(address),q.id.eq(punish.getId())).fetchOne();
            Long value=(Long)map.get(address);
            if(value==null) {
                if(count!=0) {
                    map.put(address, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(address,value);
            }
        }
        return map;
    }

    @Override
    public Long getOpCheck(HttpServletRequest request) {
        QPunish q=QPunish.punish;
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        String userUnit ="";
        String orgName="";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户的省份
             */
            orgName = userInfo.getOrgName();

        }
        Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).where(q.implementInstitution.eq(orgName),q.delFlag.eq(Constant.NO_DELETE)).fetchOne();
        return count;
    }

    @Override
    public HashMap getCountByYear(String year) {
        QPunish q=QPunish.punish;
        Predicate predicate=q.isNotNull().or(q.isNull());
        List<Punish> list=jpaQueryFactory.selectFrom(q).where(q.delFlag.eq(Constant.NO_DELETE)).fetch();
        HashMap map=new HashMap();
        for (Punish punish:list) {
            String address=punish.getImplementInstitution();
            ComparableExpressionBase<?> creatYear = q.createTime.year();
            predicate =ExpressionUtils.and(predicate,((NumberExpression) creatYear).stringValue().eq(year)) ;
            Long count=jpaQueryFactory.select(q.implementInstitution.count()).from(q).
                    where(q.delFlag.eq(Constant.NO_DELETE),q.implementInstitution.eq(address),q.id.eq(punish.getId()),predicate).fetchOne();
            Long value=(Long)map.get(address);
            if(value==null) {
                if(count!=0) {
                    map.put(address, count);
                }
            }else {
                value=count.longValue()+value.longValue();
                map.put(address,value);
            }
        }

        return map;
    }

    @Override
    public QueryResults<Punish> getAll(Pageable pageable, String superviseItemCode, String punishActionName, String caseSource, String punishType) {
        QPunish qPunish=QPunish.punish;
        Predicate predicate = qPunish.isNotNull().or(qPunish.isNull());
        predicate = ExpressionUtils.and(predicate, qPunish.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ("".equals(superviseItemCode) || superviseItemCode == null) ? predicate : ExpressionUtils.and(predicate, qPunish.superviseItemCode.like("%"+superviseItemCode+"%"));
        predicate = ("".equals(punishActionName) || punishActionName == null) ? predicate : ExpressionUtils.and(predicate, qPunish.punishActionName.like("%"+punishActionName+"%"));
        predicate = ("".equals(caseSource) || caseSource == null) ? predicate : ExpressionUtils.and(predicate, qPunish.caseSource.eq(caseSource));
        predicate = ("".equals(punishType) || punishType == null) ? predicate : ExpressionUtils.and(predicate, qPunish.punishType.eq(punishType));
        return  jpaQueryFactory
                .selectFrom(qPunish)
                .where(
                        predicate
                )
                .orderBy(qPunish.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();

    }

    @Override
    public List<Punish> getAllList(String superviseItemCode, String punishActionName, String caseSource, String punishType) {
        QPunish qPunish=QPunish.punish;
        Predicate predicate = qPunish.isNotNull().or(qPunish.isNull());
        predicate = ExpressionUtils.and(predicate, qPunish.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ("".equals(superviseItemCode) || superviseItemCode == null) ? predicate : ExpressionUtils.and(predicate, qPunish.superviseItemCode.like("%"+superviseItemCode+"%"));
        predicate = ("".equals(punishActionName) || punishActionName == null) ? predicate : ExpressionUtils.and(predicate, qPunish.punishActionName.like("%"+punishActionName+"%"));
        predicate = ("".equals(caseSource) || caseSource == null) ? predicate : ExpressionUtils.and(predicate, qPunish.caseSource.eq(caseSource));
        predicate = ("".equals(punishType) || punishType == null) ? predicate : ExpressionUtils.and(predicate, qPunish.punishType.eq(punishType));
        return  jpaQueryFactory
                .selectFrom(qPunish)
                .where(
                        predicate
                ).fetch();
    }

    @Override
    public Long getNum() {
        QPunish q=QPunish.punish;
        return jpaQueryFactory.select(q.id.count()).from(q).fetchCount();
    }

    @Override
    public List<Punish> getByIds(List<String> list) {
        QPunish q=QPunish.punish;
        return punishMapper.findAllById(list);
    }
}
